package cn.iocoder.yudao.im.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.im.domain.AiChatHistory;
import cn.iocoder.yudao.im.domain.NoticeImMessage;
import cn.iocoder.yudao.im.domain.vo.Message;
import cn.iocoder.yudao.im.domain.vo.ModelParameter;
import cn.iocoder.yudao.im.domain.vo.ModelResponse;
import cn.iocoder.yudao.im.mapper.AiChatHistoryMapper;
import cn.iocoder.yudao.im.service.AiChatHistoryService;
import cn.iocoder.yudao.im.service.NoticeImMessageService;
import cn.iocoder.yudao.im.util.AiUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * AI调用聊天记录(AiChatHistory)表服务实现类
 *
 * @author makejava
 * @since 2024-06-27 15:38:47
 */
@Service
public class AiChatHistoryServiceImpl extends ServiceImpl<AiChatHistoryMapper, AiChatHistory> implements AiChatHistoryService {

    @Resource
    AiUtil aiUtil;
    @Resource
    AiChatHistoryMapper aiChatHistoryMapper;
    @Resource
    NoticeImMessageService fancyOfficeImMessageService;

    @Override
    public String chat(String message, Boolean isHistory) {
        Long userid = SecurityFrameworkUtils.getLoginUser().getId();
        List<Message> messages = new LinkedList<>();
        ModelParameter modelParameter = new ModelParameter();
        //说明不是新开的会话内容
        if (isHistory) {
            if (!StrUtil.isNotBlank(message)) {
                message = "你好";
            }
        } else {
            List<AiChatHistory> aiChatHistories = aiChatHistoryMapper.selectList(new LambdaQueryWrapper<AiChatHistory>().eq(AiChatHistory::getState, 0).eq(AiChatHistory::getOriginatorId, userid).orderByDesc(AiChatHistory::getCreateTime).last("LIMIT 5"));
            aiChatHistories.forEach(item -> {
                messages.add(new Message(item.getProblem()));
            });
            Collections.reverse(messages);
        }
        messages.add(new Message(message));
        modelParameter.setMessages(messages);
        ModelResponse chat = aiUtil.chat(modelParameter);
        if (BeanUtil.isNotEmpty(chat)) {
            AiChatHistory aiChatHistory = new AiChatHistory();
            aiChatHistory.setOriginatorId(userid);
            aiChatHistory.setOriginatorName(SecurityFrameworkUtils.getLoginUserNickname());
            aiChatHistory.setProblem(message);
            aiChatHistory.setHistoricalRecords(isHistory);
            aiChatHistory.setModelName(chat.getModel());
            aiChatHistory.setResponseTime(chat.getCreated_at());
            aiChatHistory.setJsonContent(JSON.toJSONString(chat));
            aiChatHistory.setTextContent(chat.getMessage().getContent());
            aiChatHistory.setCreateTime(new Date());
            aiChatHistory.setState(0);
            aiChatHistoryMapper.insert(aiChatHistory);
            //开始添加聊天记录
            //请求Ai的聊天记录   和  Ai返回记录的聊天记录
            NoticeImMessage noticeImMessageVo = new NoticeImMessage();
            noticeImMessageVo.setSendId(userid);
            noticeImMessageVo.setRecvId(0L);
            noticeImMessageVo.setContent(message);
            noticeImMessageVo.setType(999);
            noticeImMessageVo.setStatus(1);
            noticeImMessageVo.setSendTime(LocalDateTime.now());
            fancyOfficeImMessageService.save(noticeImMessageVo);

            NoticeImMessage noticeImMessageVo2 = new NoticeImMessage();
            noticeImMessageVo2.setSendId(0L);
            noticeImMessageVo2.setRecvId(userid);
            noticeImMessageVo2.setContent(chat.getMessage().getContent());
            noticeImMessageVo2.setType(999);
            noticeImMessageVo2.setStatus(1);
            noticeImMessageVo2.setSendTime(LocalDateTime.now());
            fancyOfficeImMessageService.save(noticeImMessageVo2);
            return chat.getMessage().getContent();
        } else {
            return "暂无回答";
        }
    }
}
